package com.ruoyi.ewem.controller;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: Yanyanyu
 * @Date: 2024/7/30 9:33
 */
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {

    static Log log= LogFactory.get(WebSocketServer.class);

    private static int onlineCount = 0;

    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    private Session session;

    private String userId="";


    /**
     * 连接建立成功调用的方法
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){

        this.session=session;
        this.userId=userId;
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
        }else{
            webSocketMap.put(userId,this);
            addOnLineCount();
        }

        log.info("用户连接："+userId+"，当前在线人数为："+getOnlineCount());

    }

    /**
     * 连接关闭调用的方法
     * @return
     */
    @OnClose
    public void onClose(){
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            subOnlineCount();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message,Session session){

        log.info("用户消息："+userId+"，报文："+message);

        if(StringUtils.isNotBlank(message)){
            JSONObject jsonObject = JSON.parseObject(message);
        }

    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session,Throwable error){
        log.error("用户信息："+this.userId+"，原因："+error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 消息单发
     */
    public static void sendOnMessage(String userId,String message) throws IOException {

        WebSocketServer webSocketServer = webSocketMap.get(userId);
        webSocketServer.session.getBasicRemote().sendText(message);
    }

    /**
     * 实现服务器主动推送
     */
    public static void sendAllMessage(String message) throws IOException {
        ConcurrentHashMap.KeySetView<String, WebSocketServer> userIds = webSocketMap.keySet();
        for (String userId : userIds) {
            WebSocketServer webSocketServer = webSocketMap.get(userId);
            webSocketServer.session.getBasicRemote().sendText(message);
            System.out.println("webSocket实现服务器主动推送成功userIds=="+userIds);
        }
    }

    /**
     * 发送自定义消息
     */
    public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {

        log.info("发送消息到："+userId+"，报文："+message);
        if(StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户："+userId+"，不在线！");
        }

    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnLineCount() {
        WebSocketServer.onlineCount++;
    }


}
